/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package entity;

import java.sql.*;
import java.util.ArrayList;
import java.util.Collection;
import javax.ejb.*;
import javax.naming.*;
import javax.sql.DataSource;
import transfer.Warehouse;

/**
 *
 * @author Sergey
 */
public class WarehouseBean implements EntityBean {

    private EntityContext entityContext;
    private DataSource dataSource;
    private Warehouse warehouse = new Warehouse();

    public Warehouse getWarehouse() {
        return warehouse;
    }

    public void setWarehouse(Warehouse warehouse) {
        this.warehouse = warehouse;
    }

    public void setEntityContext(EntityContext entityContext) throws EJBException {
        try {
            this.entityContext = entityContext;
            Context context = new InitialContext();
            dataSource = (DataSource) context.lookup("jdbc/ossystem");
        } catch (NamingException ex) {
            throw new EJBException("Does not find jdbc/ossystem");
        }
    }

    public void unsetEntityContext() {
        entityContext = null;
    }

    public void ejbRemove() throws RemoveException {
        Connection connection = null;
        PreparedStatement statement = null;
        try {
            connection = dataSource.getConnection();
            statement = connection.prepareStatement(
                    "DELETE FROM Warehouse WHERE id_warehouse = ?");
            statement.setInt(1, warehouse.getIdWarehouse().intValue());
            if (statement.executeUpdate() < 1) {
                throw new RemoveException("deleting error");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            closeConnection(connection, statement);
        }
    }

    public void ejbActivate() {
    }

    public void ejbPassivate() {
    }

    public void ejbLoad() throws EJBException {
        Integer primaryKey = (Integer) entityContext.getPrimaryKey();
        Connection connection = null;
        PreparedStatement statement = null;
        try {
            connection = dataSource.getConnection();
            statement = connection.prepareStatement(
                    "SELECT id_address, name_warehouse, shipment_rate, shipment_speed "
                    + "FROM Warehouse WHERE id_warehouse = ?");
            statement.setInt(1, primaryKey.intValue());
            ResultSet resultSet = statement.executeQuery();
            if (!resultSet.next()) {
                throw new NoSuchEntityException("Warehouse with id = " + primaryKey + " not exists");
            }
            Context c = new InitialContext();
            AddressLocalHome addressHome = (AddressLocalHome) c.lookup("java:comp/env/Address");
            AddressLocal addressLocal = addressHome.findByPrimaryKey(new Integer(resultSet.getInt(1)));
            warehouse.setAddress(addressLocal.getAddress());
            warehouse.setNameWarehouse(resultSet.getString(2));
            warehouse.setShipmentRate(new Double(resultSet.getDouble(3)));
            warehouse.setShipmentSpeed(new Double(resultSet.getDouble(4)));
            warehouse.setIdWarehouse(primaryKey);
        } catch (SQLException ex) {
            ex.printStackTrace();
        } catch (NamingException ex) {
            ex.printStackTrace();
        } catch (FinderException ex) {
            ex.printStackTrace();
        } finally {
            closeConnection(connection, statement);
        }
    }

    public void ejbStore() throws EJBException {
        Connection connection = null;
        PreparedStatement statement = null;
        try {
            connection = dataSource.getConnection();
            statement = connection.prepareStatement(
                    "UPDATE Warehouse SET id_address = ?, name_warehouse = ?, shipment_rate = ?, shipment_speed = ? "
                    + "WHERE id_warehouse = ?");
            statement.setInt(1, warehouse.getAddress().getIdAddress().intValue());
            statement.setString(2, warehouse.getNameWarehouse());
            statement.setDouble(3, warehouse.getShipmentRate().doubleValue());
            statement.setDouble(4, warehouse.getShipmentSpeed().doubleValue());
            statement.setInt(5, ((Integer) entityContext.getPrimaryKey()).intValue());
            statement.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            closeConnection(connection, statement);
        }
    }

    public java.lang.Integer ejbFindByName(String nameWarehouse) throws FinderException {
        Connection connection = null;
        PreparedStatement statement = null;
        try {
            connection = dataSource.getConnection();
            statement = connection.prepareStatement(
                    "SELECT id_warehouse "
                    + "FROM Warehouse WHERE name_warehouse = ?");
            statement.setString(1, nameWarehouse);
            ResultSet resultSet = statement.executeQuery();
            if (!resultSet.next()) {
                throw new FinderException("Warehouse with this name is not exists");
            }
            return new Integer(resultSet.getInt(1));
        } catch (SQLException e) {
            throw new EJBException("Error in SELECT");
        } finally {
            closeConnection(connection, statement);
        }
    }

    public java.lang.Integer ejbFindByPrimaryKey(Integer idWarehouse) throws FinderException {
        Connection connection = null;
        PreparedStatement statement = null;
        try {
            connection = dataSource.getConnection();
            statement = connection.prepareStatement(
                    "SELECT id_warehouse "
                    + "FROM Warehouse WHERE id_warehouse = ?");
            statement.setInt(1, idWarehouse.intValue());
            ResultSet resultSet = statement.executeQuery();
            if (!resultSet.next()) {
                throw new FinderException("Commodity with primary key " + idWarehouse + " is not exists");
            }
            return new Integer(resultSet.getInt(1));
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        } finally {
            closeConnection(connection, statement);
        }
    }

    public void ejbPostCreate(Warehouse awarehouse) throws CreateException {
    }

    public java.lang.Integer ejbCreate(Warehouse awarehouse) throws CreateException {
        Connection connection = null;
        PreparedStatement statement = null;
        try {
            connection = dataSource.getConnection();
            Statement stat = connection.createStatement();
            Integer idWarehouse = null;
            ResultSet resultSet = stat.executeQuery("select seq.nextval from dual");
            if (resultSet.next()) {
                idWarehouse = new Integer(resultSet.getInt(1));
            }
            stat.close();
            Context c = new InitialContext();
            AddressLocalHome addressHome = (AddressLocalHome) c.lookup("java:comp/env/Address");
            addressHome.create(awarehouse.getAddress());
            warehouse.setIdWarehouse(idWarehouse);
            warehouse.setAddress(awarehouse.getAddress());
            warehouse.setNameWarehouse(awarehouse.getNameWarehouse());
            warehouse.setShipmentRate(awarehouse.getShipmentRate());
            warehouse.setShipmentSpeed(awarehouse.getShipmentSpeed());
            statement = connection.prepareStatement("INSERT INTO Warehouse"
                    + "(id_warehouse, id_address, name_warehouse, shipment_rate, shipment_speed) VALUES(?, ?, ?, ?, ?)");
            statement.setInt(1, idWarehouse.intValue());
            statement.setInt(2, awarehouse.getAddress().getIdAddress().intValue());
            statement.setString(3, awarehouse.getNameWarehouse());
            statement.setDouble(4, awarehouse.getShipmentRate().doubleValue());
            statement.setDouble(5, awarehouse.getShipmentSpeed().doubleValue());
            if (statement.executeUpdate() != 1) {
                throw new CreateException("Inserted error");
            }
            return idWarehouse;
        } catch (NamingException ex) {
            ex.printStackTrace();
            return null;
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        } finally {
            closeConnection(connection, statement);
        }
    }

    private void closeConnection(Connection connection, Statement statement) {
        try {
            if (statement != null) {
                statement.close();
            }
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
        try {
            if (connection != null) {
                connection.close();
            }
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
    }

    public Collection ejbFindAllWarehouses() throws FinderException {
        Connection connection = null;
        PreparedStatement statement = null;
        try {
            connection = dataSource.getConnection();
            statement = connection.prepareStatement(
                    "SELECT id_warehouse "
                    + "FROM Warehouse");
            ResultSet resultSet = statement.executeQuery();
            Collection result = new ArrayList();
            while (resultSet.next()) {
                result.add(new Integer(resultSet.getInt(1)));
            }
            return result;
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        } finally {
            closeConnection(connection, statement);
        }
    }
}
